package mysql

import (
	"bluebell/models"
	"errors"

	"go.uber.org/zap"
)

// CreateCollect 创建收藏记录
func CreateCollect(c *models.UserCollect) error {
	sqlStr := `INSERT INTO user_collect (user_id, post_id, created_at) VALUES (?, ?, ?)`
	_, err := db.Exec(sqlStr, c.UserID, c.PostID, c.CreatedAt)
	if err != nil {
		zap.L().Error("创建收藏记录失败",
			zap.Int64("userID", c.UserID),
			zap.Int64("postID", c.PostID),
			zap.Error(err))
		return err
	}
	zap.L().Info("成功创建收藏记录",
		zap.Int64("userID", c.UserID),
		zap.Int64("postID", c.PostID))

	return nil
}

// DeleteCollect 删除收藏记录
func DeleteCollect(userID, postID int64) error {
	sqlStr := `DELETE FROM user_collect WHERE user_id = ? AND post_id = ?`
	result, err := db.Exec(sqlStr, userID, postID)
	if err != nil {
		zap.L().Error("删除收藏记录失败",
			zap.Int64("userID", userID),
			zap.Int64("postID", postID),
			zap.Error(err))
		return err
	}

	if rowsAffected, _ := result.RowsAffected(); rowsAffected == 0 {
		return errors.New("未找到收藏记录")
	}

	zap.L().Info("成功删除收藏记录",
		zap.Int64("userID", userID),
		zap.Int64("postID", postID))
	return nil
}

// GetCollectList 获取收藏列表
func GetCollectList(userID, page, size int64) ([]*models.CollectListItem, error) {
	offset := (page - 1) * size
	if offset < 0 {
		offset = 0
	}

	sqlStr := `
		SELECT 
			p.post_id,
			p.title,
			SUBSTRING(p.content, 1, 100) AS content
		FROM user_collect uc
		JOIN post p ON uc.post_id = p.post_id
		WHERE uc.user_id = ?
		ORDER BY uc.created_at DESC
		LIMIT ? OFFSET ?
	`

	var items []*models.CollectListItem
	err := db.Select(&items, sqlStr, userID, size, offset)
	if err != nil {
		zap.L().Error("获取收藏列表失败",
			zap.Int64("userID", userID),
			zap.Error(err))
		return nil, err
	}

	// 为内容添加省略号（如果截取了）
	for _, item := range items {
		if len(item.Content) == 100 {
			item.Content += "..."
		}
	}

	zap.L().Info("成功获取收藏列表",
		zap.Int64("userID", userID),
		zap.Int("count", len(items)))
	return items, nil
}

// IsPostCollected 检查帖子是否已被收藏
func IsPostCollected(userID, postID int64) (bool, error) {
	sqlStr := `SELECT COUNT(1) FROM user_collect WHERE user_id = ? AND post_id = ?`
	var count int
	err := db.Get(&count, sqlStr, userID, postID)
	if err != nil {
		zap.L().Error("查询收藏状态失败",
			zap.Int64("userID", userID),
			zap.Int64("postID", postID),
			zap.Error(err))
		return false, err
	}

	zap.L().Debug("检查收藏状态",
		zap.Int64("userID", userID),
		zap.Int64("postID", postID),
		zap.Bool("collected", count > 0))
	return count > 0, nil
}
